<!--
 * @Author: weikang
 * @Description:
 * @Date: 2024-01-21 16:34:04
 * @LastEditTime: 2024-06-15 14:03:56
 * @FilePath: \env-manager-pc\src\views\data_query\pollute_err\err.detail.vue
-->
<script setup lang="ts">
import dayjs from 'dayjs'
import { ElMessage, ElMessageBox } from 'element-plus'
import lineChart from './components/lineChart.vue'
import { useErrHook } from './components/errHook'
import Inspecting from './components/Inspecting.vue'
import declartion from './components/declartion.vue'
import useEntStore from '@/store/modules/ent'
import type { PolluteErrRow } from '@/api/modules/types/data.query'
import { DeclareState } from '@/api/modules/types/data.query'
import { DeviceType } from '@/utils/dataHook/devices'
import useKeepAliveStore from '@/store/modules/keepAlive'
import { repaceUrl } from '@/utils'
import { statusType } from '@/views/data_query/declare/page'
import useUserStore from '@/store/modules/user'
import { ModelType } from '@/types/common'
import dataQueryApi from '@/api/modules/data.query'

const keepAliveStore = useKeepAliveStore()

onBeforeRouteLeave((to) => {
  if (to.name !== 'data-pollute-err-list') {
    keepAliveStore.remove('DataPolluteErrList')
  }
})

const entStore = useEntStore()
const userStore = useUserStore()
const loading = ref(false)

const cwRef = ref()
const ZwRef = ref()
const inspectingRef = ref()
const declartionRef = ref()

const route = useRoute()
const deviceInfo: PolluteErrRow = JSON.parse(sessionStorage.getItem('PolluteErrRow') || '{}')
const deviceId = ref(route.params.id as string)
const type = ref(route.query.type as DeviceType)

function currentChange(val: any) {
  if (val.type !== DeviceType.Produce && val.type !== DeviceType.Reuse && val.type !== DeviceType.ReuseParts) {
    return
  }
  if (val.ObjID) {
    repaceUrl(`/data-query/pollute-err/electric/${val.ObjID}`, { type: val.type })
    type.value = val.type
    deviceId.value = val.ObjID
  }
}
const currentTime = ref(route.query.currentTime as string || dayjs().format('YYYY-MM-DD HH:mm:ss'))

const currentData = computed(() => {
  if (!deviceId) {
    return null
  }
  switch (type.value) {
    case DeviceType.Produce:
      return entStore.currentEntData.Produces[deviceId.value]
    case DeviceType.Reuse:
      return entStore.currentEntData.AllReuses[deviceId.value]
    case DeviceType.ReuseParts:
      return entStore.currentEntData.Reuses[deviceId.value]
    default:
      return null
  }
})

const startTime = computed(() => {
  return dayjs(currentTime.value).format('YYYY-MM-DD')
})
const endTime = computed(() => {
  return dayjs(currentTime.value).add(1, 'day').format('YYYY-MM-DD')
})

const Reuses = computed(() => {
  if (!currentData.value) {
    return []
  }
  if (type.value === DeviceType.ReuseParts) {
    return currentData.value.ReuseParts
  }
  else if (type.value === DeviceType.Reuse) {
    return [currentData.value]
  }
  else if (type.value === DeviceType.Produce) {
    const { Reuses } = entStore.currentEntData
    const dataList: any = []
    currentData.value.ReuseIDs.forEach((key: string) => {
      Reuses[key].ReuseParts.forEach((item: any) => {
        dataList.push(item)
      })
    })
    return dataList
  }
})

function changeDay(type: string) {
  if (type === 'next') {
    currentTime.value = dayjs(currentTime.value).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  }
  else {
    currentTime.value = dayjs(currentTime.value).subtract(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  }
  refresh()
}

function changeTime(value: any) {
  currentTime.value = value
  refresh()
}

const { ProduceTotals, ReuseTotals, Items, getErrorData } = useErrHook(currentData, startTime, endTime)
async function refresh() {
  await getErrorData()
  cwRef.value && cwRef.value.refresh()
  ZwRef.value && ZwRef.value.refresh()
}

watch(
  () => currentData.value,
  () => {
    if (currentData.value) {
      refresh()
    }
  },
)

function durationTime(row: any) {
  const diffTime = dayjs(row.EndTime || undefined).diff(
    dayjs(row.StartTime),
    'm',
  )
  const minute = diffTime % 60
  const hour = Math.floor(diffTime / 60)
  return `${hour}小时${minute}分钟`
}

function approve(row: any) {
  inspectingRef.value?.open({
    data: row,
  })
}

function addDeclear(row: any) {
  declartionRef.value?.open({
    type: ModelType.add,
    data: row,
  })
}

function approveSubmit(data: { data: any, isPass: boolean }) {
  const { ProduceObjID, ReusePartObjID, StartTime, inspectContent, inspectName, inspectTel } = data.data
  const formData = {
    produceObjID: ProduceObjID || null,
    reusePartObjID: ReusePartObjID,
    startTime: StartTime,
    inspectContent,
    inspectName,
    inspectTel,
  }

  ElMessageBox.confirm(`确认提交${data.isPass ? '通过' : '驳回'}审核吗？`, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    const api = data.isPass ? dataQueryApi.ReuseExDeclareEnvOrgPass : dataQueryApi.ReuseExDeclareEnvOrgBack
    api(formData).then(() => {
      ElMessage({
        type: 'success',
        message: '提交成功',
      })
      inspectingRef.value?.close()
      getErrorData()
    })
  })
}

function declearSubmit(formData: any) {
  const { ProduceObjID, ReusePartObjID, StartTime, ReportContent, ReportName, ReportTel } = formData
  const data = {
    produceObjID: ProduceObjID || null,
    reusePartObjID: ReusePartObjID,
    startTime: StartTime,
    reportContent: ReportContent,
    reportName: ReportName,
    reportTel: ReportTel,
  }
  dataQueryApi.ReuseExDeclareEnt(data).then((res) => {
    declartionRef.value.upload(res)
    ElMessage({
      type: 'success',
      message: '提交成功',
    })
    declartionRef.value?.close()
    getErrorData()
  })
}

function toView(row: any) {
  if (userStore.isEnterpris) {
    declartionRef.value?.open({
      type: ModelType.readonly,
      data: row,
    })
  }
  else {
    inspectingRef.value?.open({
      type: ModelType.readonly,
      data: row,
    })
  }
}
</script>

<template>
  <PageMain>
    <div class="flex">
      <div class="mr-20px w-300px flex-shrink-0 b-r-1px b-r-#EBEEF5 b-r-solid pr-10px">
        <EntDeviceTree :ent-id="deviceInfo.EntObjID" :device-id="deviceId" @current-change="currentChange" />
      </div>
      <div class="flex-grow-1 overflow-x-hidden">
        <div>
          <el-date-picker v-model="currentTime" type="date" value-format="YYYY-MM-DD HH:mm:ss" @change="changeTime" />
          <el-button-group class="ml-10px">
            <el-button type="primary" @click="changeDay('prev')">
              前一天
            </el-button>
            <el-button type="primary" @click="changeDay('next')">
              后一天
            </el-button>
            <el-button type="primary" @click="changeDay('next')">
              详细信息
            </el-button>
          </el-button-group>
        </div>
        <lineChart
          v-if="type !== DeviceType.Reuse" ref="cwRef" :produce-data="currentData" is-cw
          :start-time="startTime" :end-time="endTime" :error-time="ProduceTotals"
        />
        <lineChart
          v-if="Reuses.length" ref="ZwRef" :produce-data="currentData" :start-time="startTime"
          :end-time="endTime" :reuses="Reuses" :error-time="ReuseTotals"
        />
        <vxe-table border :data="Items" :loading="loading" :row-config="{ isCurrent: true }">
          <VxeColumn type="seq" title="序号" width="80" />
          <VxeColumn field="ReuseName" title="治理设施" min-width="100" />
          <VxeColumn field="ReusePartName" title="治理环节" min-width="100" />
          <VxeColumn field="StartTime" title="发生时间" width="200" />
          <VxeColumn field="EndTime" title="恢复时间" width="200" />
          <VxeColumn field="ReportTime" title="时长" width="200">
            <template #default="{ row }">
              {{ durationTime(row) }}
            </template>
          </VxeColumn>
          <VxeColumn field="DeclareStateName" title="申报状态" width="200">
            <template #default="{ row }">
              <el-tag :type="statusType(row.DeclareStateID)">
                {{ row.DeclareStateName }}
              </el-tag>
            </template>
          </VxeColumn>
          <VxeColumn title="操作" width="200">
            <template #default="{ row }">
              <el-button v-if="userStore.isEnterpris && row.DeclareStateID === DeclareState.Declaring" type="primary" link @click="addDeclear(row)">
                申报
              </el-button>
              <el-button v-if="userStore.isEnterpris && row.DeclareStateID === DeclareState.DeclareFail" type="primary" link @click="addDeclear(row)">
                再次申报
              </el-button>
              <el-button v-else-if="userStore.isEnvOrg && row.DeclareStateID === DeclareState.Inspecting" type="primary" link @click="approve(row)">
                审批
              </el-button>
              <el-button v-else type="primary" link @click="toView(row)">
                查看
              </el-button>
            </template>
          </VxeColumn>
        </vxe-table>
      </div>
    </div>
    <Inspecting ref="inspectingRef" @submit="approveSubmit" />
    <declartion ref="declartionRef" @submit="declearSubmit" />
  </PageMain>
</template>
